/**
 * 🎮 游戏化功能自动初始化
 * 后端启动时自动创建游戏化表和数据
 */

const db = require('./database');

async function initGamification() {
    try {
        console.log('🎮 正在初始化游戏化功能...');

        // 检查数据库连接
        const connection = await db.getConnection();
        
        // 1. 创建成就定义表
        await connection.query(`
            CREATE TABLE IF NOT EXISTS achievements (
                achievement_id INT PRIMARY KEY AUTO_INCREMENT,
                achievement_key VARCHAR(50) UNIQUE NOT NULL COMMENT '成就唯一标识',
                achievement_name VARCHAR(100) NOT NULL COMMENT '成就名称',
                achievement_desc TEXT COMMENT '成就描述',
                achievement_icon VARCHAR(20) DEFAULT '🏆' COMMENT '成就图标',
                achievement_type ENUM('basic', 'streak', 'saving', 'category', 'budget') DEFAULT 'basic' COMMENT '成就类型',
                points INT DEFAULT 10 COMMENT '奖励积分',
                requirement_value INT DEFAULT 1 COMMENT '达成要求值',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='成就定义表'
        `);

        // 2. 创建用户成就记录表
        await connection.query(`
            CREATE TABLE IF NOT EXISTS user_achievements (
                id INT PRIMARY KEY AUTO_INCREMENT,
                user_id INT NOT NULL,
                achievement_id INT NOT NULL,
                achieved_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                UNIQUE KEY uk_user_achievement (user_id, achievement_id),
                FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE,
                FOREIGN KEY (achievement_id) REFERENCES achievements(achievement_id) ON DELETE CASCADE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户成就记录表'
        `);

        // 3. 创建用户等级信息表
        await connection.query(`
            CREATE TABLE IF NOT EXISTS user_levels (
                user_id INT PRIMARY KEY,
                level INT DEFAULT 1 COMMENT '当前等级',
                exp INT DEFAULT 0 COMMENT '当前经验值',
                total_points INT DEFAULT 0 COMMENT '总积分',
                total_records INT DEFAULT 0 COMMENT '总记账次数',
                streak_days INT DEFAULT 0 COMMENT '连续记账天数',
                last_record_date DATE COMMENT '最后记账日期',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户等级信息表'
        `);

        // 4. 创建等级配置表
        await connection.query(`
            CREATE TABLE IF NOT EXISTS level_config (
                level INT PRIMARY KEY,
                level_name VARCHAR(50) NOT NULL COMMENT '等级名称',
                level_icon VARCHAR(20) DEFAULT '⭐' COMMENT '等级图标',
                required_exp INT NOT NULL COMMENT '所需经验值',
                unlocks TEXT COMMENT '解锁功能（JSON格式）',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='等级配置表'
        `);

        // 5. 检查并插入预设成就
        const [achievements] = await connection.query('SELECT COUNT(*) as count FROM achievements');
        if (achievements[0].count === 0) {
            await connection.query(`
                INSERT INTO achievements (achievement_key, achievement_name, achievement_desc, achievement_icon, achievement_type, points, requirement_value) VALUES
                ('first_record', '初次记账', '添加第一条收支记录', '🎉', 'basic', 10, 1),
                ('record_10', '记账新手', '累计记账10次', '📝', 'basic', 20, 10),
                ('record_50', '记账达人', '累计记账50次', '📊', 'basic', 50, 50),
                ('record_100', '记账专家', '累计记账100次', '💎', 'basic', 100, 100),
                ('record_365', '记账传奇', '累计记账365次', '👑', 'basic', 500, 365),
                ('streak_7', '坚持一周', '连续记账7天', '🔥', 'streak', 30, 7),
                ('streak_30', '坚持一月', '连续记账30天', '💪', 'streak', 100, 30),
                ('streak_100', '百日坚持', '连续记账100天', '🏆', 'streak', 300, 100),
                ('save_month', '节省达人', '本月支出少于上月', '💰', 'saving', 50, 1),
                ('save_3months', '节省大师', '连续3个月支出递减', '🌟', 'saving', 150, 3),
                ('category_5', '分类入门', '使用5种不同分类', '🎯', 'category', 25, 5),
                ('category_all', '分类大师', '使用过所有支出分类', '🗺️', 'category', 100, 9),
                ('budget_keep', '精打细算', '支出控制在预算内', '💎', 'budget', 50, 1),
                ('budget_3months', '预算专家', '连续3个月支出控制在预算内', '⭐', 'budget', 200, 3)
            `);
            console.log('✅ 成就数据已插入');
        }

        // 6. 检查并插入等级配置
        const [levels] = await connection.query('SELECT COUNT(*) as count FROM level_config');
        if (levels[0].count === 0) {
            await connection.query(`
                INSERT INTO level_config (level, level_name, level_icon, required_exp, unlocks) VALUES
                (1, '新手', '🌱', 0, '{"features": ["基础记账"]}'),
                (2, '学徒', '📝', 100, '{"features": ["基础记账", "快捷记账"]}'),
                (3, '行家', '💼', 300, '{"features": ["基础记账", "快捷记账", "预算管理"]}'),
                (4, '大师', '🎓', 800, '{"features": ["基础记账", "快捷记账", "预算管理", "高级统计"]}'),
                (5, '传奇', '👑', 2000, '{"features": ["所有功能", "自定义主题", "专属徽章"]}'),
                (6, '宗师', '⚡', 5000, '{"features": ["所有功能", "自定义主题", "专属徽章", "数据分析"]}')
            `);
            console.log('✅ 等级配置已插入');
        }

        // 7. 为现有用户初始化等级数据
        await connection.query(`
            INSERT IGNORE INTO user_levels (user_id, level, exp, total_points)
            SELECT user_id, 1, 0, 0 FROM users
            WHERE user_id NOT IN (SELECT user_id FROM user_levels)
        `);

        // 8. 创建触发器
        try {
            await connection.query('DROP TRIGGER IF EXISTS after_user_insert');
            await connection.query(`
                CREATE TRIGGER after_user_insert
                AFTER INSERT ON users
                FOR EACH ROW
                INSERT INTO user_levels (user_id, level, exp, total_points)
                VALUES (NEW.user_id, 1, 0, 0)
            `);
            console.log('✅ 触发器已创建');
        } catch (error) {
            console.log('⚠️  触发器创建跳过');
        }

        connection.release();
        console.log('✅ 游戏化功能初始化完成！');
        return true;
    } catch (error) {
        console.error('⚠️  游戏化功能初始化失败:', error.message);
        console.log('💡 游戏化功能将不可用，但不影响核心功能');
        return false;
    }
}

module.exports = initGamification;

